<template>
	  <uni-popup ref="popupRef" background-color="#fff" borderRadius="12px 12px 12px 12px" type="dialog" @change="popupChange">
      <view class="popup-content">
				<view class="popup-header">
					<view class="header-title">{{title}}</view>
					<image class="header-close" src="../static/icon-guanbi.png" @tap="hidePopup"></image>
				</view>
				<view class="popup-picture">
					<view class="item-picture" @tap="chooseImage('groupAvart')">
						<image v-if="!state.groupAvart" class="icon-photo" src="../static/icon-photo.png"></image>
						<image v-else class="avart" :src="state.groupAvart"></image>
						<view class="item-tip">
							<text>{{state.groupAvart ? '重新上传' : '设置头像'}}</text>
							<text class="icon-requied">*</text>
						</view>
					</view>
					<view class="item-picture" @tap="chooseImage('groupPicture')">
						<image v-if="!state.groupPicture" class="icon-photo" src="../static/icon-photo.png"></image>
						<image v-else class="avart" :src="state.groupPicture"></image>
						<view class="item-tip">
							<text>{{state.groupPicture ? '重新上传' : '上传团队合照背景'}}</text>
						</view>
					</view>
				</view>
				<view class="group-name">
					<view class="label">
						<text>跑团名称</text>
						<text class="icon-requied">*</text>
					</view>
					<input class="uni-input" :value="state.groupName" maxlength="20" placeholder="请输入跑团名称" @blur="onBlur"/>
				</view>
				<button
					type="primary"
					class="common-btn"
					@tap="saveAvartInfo"
				>
					确定
				</button>
			</view>
    </uni-popup>
</template>

<script setup name="PictureUpload">
import { onLaunch, onShow, onHide, onUnload } from "@dcloudio/uni-app";
import { reactive, ref, toRefs, watch, onMounted, getCurrentInstance, nextTick } from 'vue';
import * as API from "../../api/api"
import { storeToRefs } from "pinia";
import { useRunInfoStore } from "../../store/runInfo";
import { useGroupStore } from "@/store/group";
const useGroupData = useGroupStore()
const useRunInfoData = useRunInfoStore()
const { proportionShow, initStatus, timerNum, centerDistance, runType } = storeToRefs(useRunInfoData)
const { groupInfo, groupType } = storeToRefs(useGroupData)
const appInstance = getCurrentInstance().proxy
const props = defineProps({
  tipTxt: {
    type: String,
    default: "请阅读并勾选用户协议"
  },
  title: {
    type: String,
    default: '创建跑团'
  },
  groupName: {
    type:String,
    default: ''
  },
  type: {
    type: String,
    default: 'create'
  },
  uuid: {
    type: String,
    default: ''
  },
  getRankingData: Function
})

const { tipTxt, title, groupName, type, uuid }  = toRefs(props)
const popupRef = ref(null)

const state = reactive({
	groupAvart: null,
	groupPicture: null,
	groupName: null,
	userInfo: null,
  isClickTwo: true
})

const popupChange = (e) => {
  console.log(e, 988888)
  if (e.show && type.value === 'update') {
    state.groupAvart = groupInfo.value?.groupHeadImage
    state.groupPicture = groupInfo.value?.groupPhoto
    state.groupName = groupInfo.value?.groupName
  }
}

const hidePopup = () => {
	popupRef.value.close("bottom")
  useRunInfoData.setPictureUpload(false)
}

const openPopup = () => {
	popupRef.value.open("bottom")
}

const onBlur = (e) => {
	state.groupName = e?.detail?.value
}

// 创建跑团
const onCreateGroupInfo = () => {
  if (!state.isClickTwo) return
  state.isClickTwo = false
  uni.showLoading({
    title: "加载中...",
    icon: "none"
  })
	let params = {
		groupName: state.groupName, //团名称
		groupHeadImage: state.groupAvart, //团头像
		groupPhoto: state.groupPicture, //团背景图
		userId: state.userInfo?.customers?.customerId, //用户id
    groupType: groupType?.value || 0// 团类型
	}
  if (type.value === 'update') {
    params.uuid = uuid.value
  }
  const fun = type.value === 'update' ? API.updateGroupInfo : API.createGroupInfo
  fun(params).then(res => {
    uni.hideLoading()
		if (res.code === 0) {
			uni.showToast({
				title: type.value === 'update' ? '编辑成功' : "创建成功",
				icon: "none"
			})
			hidePopup()
			useGroupData.onGetGroupInfo().then(res => {
				props.getRankingData()
      })
      state.isClickTwo = true
		} else {
      state.isClickTwo = true
      uni.showToast({
        title: res.message,
        icon: "none"
      })
    }
	}).catch(err => {
    state.isClickTwo = true
    uni.hideLoading()
	})
}

const saveAvartInfo = () => {
	if (!state.groupAvart) {
		uni.showToast({
			title: "请选择跑团头像",
			icon: "none"
		})
		return
	}
	if (!state.groupName) {
		uni.showToast({
			title: "请输入跑团名称",
			icon: "none"
		})
		return
	}
	if (state.groupName && state.groupName.length > 20) {
		uni.showToast({
			title: "最多可输入20字",
			icon: "none"
		})
		return
	}
	onCreateGroupInfo()
}

const chooseImage = (type) => {
	uni.chooseImage({
		count: 1, // 最多可以选择的图片张数，默认1张
		sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认都有
		sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认都有
		success: function(res) {
			// res.tempFilePaths为选择的图片的本地临时文件路径列表
			var filePath = res.tempFilePaths[0];
			console.log("filePath", filePath)
			// state[type] = filePath
			// 在这里可以进行图片上传的相关操作
			onUploadFile(type, filePath)
		}
	})
}

const onUploadFile = (type, filePath) => {
	uni.uploadFile({
		url: API.uploadFile, // 替换为你的服务器地址
		filePath,                       // 上传的文件路径
		name: 'file', // 后端接收文件的参数名
		formData: {
			// key: res.data.key,
			// policy: res.data.policy,
			// OSSAccessKeyId: res.data.accessId,
			// signature: res.data.signature,
			// success_action_status: "200",
			// 'x-oss-security-token': securityToken // 使用STS签名时必传。
		},
		success: (uploadFileRes) => {
			console.log('---上传成功:', JSON.parse(uploadFileRes.data).data)
			state[type] = JSON.parse(uploadFileRes.data).data
		},
		fail: (err) => {
			console.error('上传失败:', err)
		},
		complete: (uploadFileRes) => {
		}
	})
}


onShow(() => {
	state.userInfo = uni.getStorageSync("userInfo") ? JSON.parse(uni.getStorageSync("userInfo")) : null
  state.isClickTwo = true
})

watch(() => initStatus.value, (newValue, oldValue) => {

}, {imediate: true})

defineExpose({
  openPopup,
  hidePopup
})

</script>

<style lang="scss">
	.popup-content{
		width: 100vw;
		height: 720rpx;
		padding: 32rpx;
		box-sizing: border-box;
		.popup-header{
			display: flex;
			justify-content: space-between;
			.header-title{
				font-weight: 500;
				font-size: 36rpx;
				color: #1C1C1E;
			}
			.header-close{
				width: 56rpx;
				height: 56rpx;
			}
		}
	}
	.popup-picture{
		display: flex;
		justify-content: center;
		.item-picture{
			width: 180rpx;
			height: 180rpx;
			background: #F7F8FA;
			border-radius: 16rpx;
			position: relative;
			text-align: center;
			margin-top: 80rpx;
      border-radius: 16rpx;
      overflow: hidden;
			&:first-child{
				margin-right: 84rpx;
			}
			.avart{
				width: 100%;
				height: 100%;
			}
			.icon-photo{
				width: 52rpx;
				height: 44rpx;
				margin-top: 60rpx;
			}
			.item-tip{
				width: 180rpx;
				height: 44rpx;
				background: rgba(0,0,0,0.5);
				border-radius: 0rpx 0rpx 16rpx 16rpx;
				position: absolute;
				bottom: 0;
				left: 0;
				font-size: 20rpx;
				color: #fff;
				text-align: center;
				line-height: 44rpx;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
	}
	.group-name{
		display: flex;
		align-items: center;
		margin: 72rpx 0 60rpx;
		label{
			font-size: 32rpx;
			color: #1C1C1E;
		}
	}
	.icon-requied{
		font-size: 32rpx;
		color: #F55858;
	}
</style>
